Print lots of stars


Posted by Christy on 2022-04-19

Description: Write a function named stars that accepts a number n and print the star patterns like below.

Note: Don’t use repeat()

stars(1)
*

stars(3)
*
**
***

stars(7)
*
**
***
****
*****
******
*******

Let's dismantle this question here, print a row of star first like below:

function stars(n) {
  let star = "";
  for (let i = 1; i <= n; i++) {
    star += "*";
  }
  console.log(star);
}

stars(3); // ***

Every line is a for loop and there're three lines so do a for loop again

function stars(n) {
  for (let i = 1; i <= n; i++) {
    let star = "";
    for (let j = 1; j <= i; j++) {
      star += "*";
    }
    console.log(star);
  }
}

stars(3);

Reflection:

n equals the times of output, if n = 3, the output is 3

Every output has the count of stars

it’s a for loop inside a for loop

Another answer:

function stars(n) {
  let star = "";
  for (let i = 1; i <= n; i++) {
    console.log((star += "*"));
  }
}

stars(3);









Related Posts

合併排序(Merge Sort)

合併排序(Merge Sort)

npm ERR! enoent ENOENT: no such file or directory, open ... package.json

npm ERR! enoent ENOENT: no such file or directory, open ... package.json

C 語言練習程式(2) -- 指標相關程式集錦

C 語言練習程式(2) -- 指標相關程式集錦


Comments